package com.luoke.dao.impl;


import cn.hutool.log.StaticLog;
import com.luoke.context.GlobalDataStore;
import com.luoke.dao.BattleDao;
import com.luoke.pojo.dto.InitiateBattleDTO;
import com.luoke.pojo.dto.PetChooseDTO;
import com.luoke.pojo.entity.Battle;
import com.luoke.pojo.entity.BattlePet;
import com.luoke.util.DatabaseUtil;
import com.luoke.util.myjdbc.SQLEnum;
import com.luoke.util.myjdbc.SQLExecute;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BattleDaoImpl implements BattleDao {

    /**
     * 获取所有在线的玩家
     *
     * @return
     */
    @Override
    public List<String> getOnlinePlayers() {

//        SQLExecute sqlExecute = new SQLExecute();
//        ResultSet resultSet = sqlExecute.executeApply("", SQLEnum.SELECT, null);


        String sql = "SELECT name FROM user WHERE online = 1";
        try {
            return DatabaseUtil.selectAll(sql, String.class);
        } catch (SQLException | ReflectiveOperationException e) {
            throw new RuntimeException("查询在线玩家失败", e);
        }
    }

    /**
     * 查询用户战斗中携带的宠物
     *
     * @param username
     * @return
     */
    @Override
    public String getUserPetList(String username) {
        SQLExecute sqlExecute = new SQLExecute();
        StringBuilder result;
        try (
                PreparedStatement preparedStatement = sqlExecute.executeApply(
                        "SELECT  pet.`name` " +
                                "FROM `user` " +
                                "LEFT JOIN user_pet ON `user`.id = user_pet.user_id " +
                                "LEFT JOIN pet ON user_pet.pet_id = pet.id " +
                                "WHERE `user`.name = '" + username + "'", SQLEnum.SELECT, null);
                ResultSet resultSet = preparedStatement.executeQuery();
        ) {
            result = new StringBuilder();
            int count = 1;

            while (resultSet.next()) {
                result.append(" ").append(count).append(". ").append(resultSet.getString("name"));
                count++;
            }
        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return result.toString();
    }

    /**
     * 初始化战斗表
     *
     * @param data
     * @return
     */
    @Override
    public Long initBattleTableAndBPetTable(InitiateBattleDTO data) {
        Battle battle = new Battle();
        battle.setInitiatorName(data.getInitiatorName());
        battle.setOpponentName(data.getOpponentName());
        Long insertKey = this.insert(battle); //完成战斗表的初始化 ，返回战斗表的主键


        String sql = "INSERT INTO battle_pet (battle_id, owner_player_id, pet_id, hp, mp, position, pet_name) SELECT " + insertKey + " AS battle_id,u.user_id AS owner_player_id,u.pet_id AS pet_id,p.hp AS hp,p.mp AS mp,u.position AS position,p.name as pet_name FROM user_pet u LEFT JOIN pet p ON u.pet_id = p.id WHERE u.user_id = (SELECT id FROM `user` WHERE `name` = ?)";

        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
            // 设置 SQL 参数
            preparedStatement.setString(1, data.getInitiatorName());

            // 执行 SQL
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }

        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS)) {
            // 设置 SQL 参数
            preparedStatement.setString(1, data.getOpponentName());

            // 执行 SQL
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }

return insertKey;
    }


    /**
     * 保存用户首发的宠物
     *
     * @param petChooseDTO
     */
    @Override
    public void savePetChoose(PetChooseDTO petChooseDTO) {

        String sql = "UPDATE battle_pet SET is_active = 1 WHERE owner_player_id = (SELECT id FROM `user` WHERE `name` = ?) AND pet_id = (SELECT pet_id FROM `user_pet` WHERE `position` = " + petChooseDTO.getCurrentChoosePet() + " AND `user_id` = (SELECT id FROM `user` WHERE `name` = ?));";
//        System.out.println(petChooseDTO.toString());
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置 SQL 参数
            preparedStatement.setString(1, petChooseDTO.getCurrentUser());
            preparedStatement.setString(2, petChooseDTO.getCurrentUser());
            // 执行 SQL
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }

    }

    @Override
    public int getBattlePetIsActive(String username) {
        int count=0;
        String sql = "SELECT COUNT(*) FROM battle_pet WHERE owner_player_id = (SELECT id FROM `user` WHERE `name` = ?) AND is_active = 1 and battle_id=?;";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置 SQL 参数
            preparedStatement.setString(1, username);
            preparedStatement.setLong(2, GlobalDataStore.getBattleIdByPlayerName(username));
            // 执行 SQL
            try (ResultSet resultSet = preparedStatement.executeQuery()) {

                if (resultSet.next()) {
                    count = resultSet.getInt(1);
                }
            }

        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }

        return count;
    }

    /**
     * 根据战斗用户名查对应首发战斗宠物的敏捷值
     * @param username
     * @return
     */
    @Override
    public int getPetDexterityByBattleUsername(String username) {

        int dexterity = 0;
        String sql = "SELECT attribute.dexterity FROM attribute LEFT JOIN pet ON attribute.id = pet.attribute_id LEFT JOIN battle_pet ON battle_pet.pet_id = pet.id WHERE battle_pet.is_active = 1 AND battle_pet.owner_player_id = (SELECT id FROM `user` WHERE `name` = ?)";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置 SQL 参数
            preparedStatement.setString(1, username);
            // 执行 SQL
            try (ResultSet resultSet = preparedStatement.executeQuery()) {

                if (resultSet.next()) {
                    dexterity = resultSet.getInt(1);
                }
            }

        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }
        return dexterity;
    }


    @Override
    public List<BattlePet> getBattlePetList(String initiatorName) {
        List<BattlePet> list=new ArrayList<>();
        String sql = "SELECT * from  battle_pet where battle_id =? and is_active = 1";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置 SQL 参数
            preparedStatement.setLong(1, GlobalDataStore.getBattleIdByPlayerName(initiatorName));
            // 执行 SQL
            try (ResultSet resultSet = preparedStatement.executeQuery()) {

                while (resultSet.next()) {
                    BattlePet battlePet = new BattlePet();
                    battlePet.setId(resultSet.getLong("id"));
                    battlePet.setBattleId(resultSet.getLong("battle_id"));
                    battlePet.setOwnerPlayerId(resultSet.getLong("owner_player_id"));
                    battlePet.setPetId(resultSet.getLong("pet_id"));
                    battlePet.setHp(resultSet.getInt("hp"));
                    battlePet.setMp(resultSet.getInt("mp"));
                    battlePet.setIsActive(resultSet.getInt("is_active"));
                    battlePet.setIsAlive(resultSet.getInt("is_alive"));
                    battlePet.setPosition(resultSet.getInt("position"));
                    battlePet.setPetName(resultSet.getString("pet_name"));

                    list.add(battlePet);
                }
            }

        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void updateBattlePetMp(String userName, Integer value, Long id) {
        String sql = "UPDATE battle_pet SET mp = mp+? WHERE battle_id = ? and owner_player_id=? and is_active=1;";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置 SQL 参数
            preparedStatement.setInt(1, value);
            preparedStatement.setLong(2, GlobalDataStore.getBattleIdByPlayerName(userName));
            preparedStatement.setLong(3,id);
            // 执行 SQL
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void updateBattlePetHp(String userName, Integer value, Long id) {
        String sql = "UPDATE battle_pet SET hp = hp+? WHERE battle_id = ? and owner_player_id=? and is_active=1;";
        try (Connection connection = DatabaseUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            // 设置 SQL 参数
            preparedStatement.setInt(1, value);
            preparedStatement.setLong(2, GlobalDataStore.getBattleIdByPlayerName(userName));
            preparedStatement.setLong(3,id);
            // 执行 SQL
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            StaticLog.error(e.getMessage());
            e.printStackTrace();
        }
    }


}
